<?php
/**
 * Created by XjHome.
 * User: xj
 * Date: 2015/4/11
 * Time: 22:10
 *  回调函数与验证类
 */

namespace Home\Controller;
define('TOKEN', '654789852');

class WechatCallBackController
{   //TOKEN验证

    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    //获取用户发送来的数据
    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];


        if (!empty($postStr)) {
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $msgType = trim($postObj->MsgType);
            //判断用户发送的信息类型
            $Callback = new CallbackController();
            switch ($msgType) {
                case "text":
                    $resultStr = $Callback->receiveText($postObj);

                    break;
                case "image":
                    $resultStr = $Callback->receiveImage($postObj);
                    break;
                case "location":
                    $resultStr = $Callback->receiveLocation($postObj);
                    break;
                case "voice":
                    $resultStr = $Callback->receiveVoice($postObj);
                    break;
                case "video":
                    $resultStr = $Callback->receiveVideo($postObj);
                    break;
                case "link":
                    $resultStr = $Callback->receiveLink($postObj);
                    break;
                case "event":
                    $resultStr = $Callback->receiveEvent($postObj);
                    break;
            }

            if ($resultStr) {
                echo $resultStr;

            } else {
                echo "Input something...";
            }
        } else {
            echo "";
            exit;
        }
    }



}

?>